<template>
  <div class="bug-trude-container">
    <div class="bug-trude-container__title">{{ props.title }}</div>
    <div class="bug-trude-container__date">
      <a-range-picker picker="month" v-model:value="rangeDate" />
    </div>
    <div ref="chartsRef" style="width: 100%" :style="{ height: props.height + 'px' }"></div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, Ref, watch, onMounted, onUnmounted } from 'vue';
  import dayjs from 'dayjs';
  import type { Dayjs } from 'dayjs';
  import { useECharts } from '/@/hooks/web/useECharts';

  type RangeValue = [Dayjs, Dayjs];
  // 默认值一整年
  const chartsRef = ref<HTMLDivElement>();
  const start = dayjs(new Date().setMonth(0));
  const end = dayjs(new Date().setMonth(11));
  const rangeDate = ref<RangeValue>([start, end]);
  const monthes = ref(new Array(12).fill(0).map((_item, i) => `${start.year()}年${i + 1}月`)); // 月份集合
  const { setOptions } = useECharts(chartsRef as Ref<HTMLDivElement>);
  const props = defineProps({
    title: {
      type: String,
      default: '',
    },
    number: {
      type: Number,
      default: 0,
    },
    height: {
      type: Number,
      default: 350,
    },
    // 横轴的类型，字符串数组
    xAxisCategory: {
      type: Array as PropType<string[] | number[]>,
      default: () => [],
    },
    // 每一列的数据
    yData: {
      type: Array as PropType<string[] | number[]>,
      default: () => [],
    },
    // 正式的数据传到这个参数中
    data: {
      type: Array as PropType<{ name: string; data: number[] }[]>,
      default: () => [],
    },
    unit: {
      type: String,
      default: '个',
    },
  });
  const emits = defineEmits(['change-range']);

  watch(rangeDate, () => {
    const diffMonth = rangeDate.value[1].diff(rangeDate.value[0], 'M');
    const month = new Array(diffMonth + 1).fill(0);
    monthes.value = month.map((_item, i) => dayjs(rangeDate.value[0]).add(i, 'M').format('YYYY年MM月'));
    methods.reload();
    emits('change-range', rangeDate);
  });

  const methods = {
    reload() {
      setOptions({
        legend: {
          selectedMode: true,
        },
        tooltip: {
          trigger: 'axis',
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: monthes.value,
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            rotate: 45,
            formatter: (value) => `${value}${props.unit}`,
          },
        },
        series: props.data.map((item) => ({
          name: item.name,
          type: 'line',
          data: item.data,
        })),
      });
    },
  };
  var timer: TimeoutHandle | null = null;
  const deshark = (callback: () => void) => {
    timer && clearTimeout(timer);
    timer = setTimeout(() => {
      callback();
    }, 50);
  };

  const myObserver = new ResizeObserver(() => {
    // 宽度发生了变化
    deshark(methods.reload);
  });

  onMounted(() => {
    methods.reload();
    if (chartsRef.value) {
      myObserver.observe(chartsRef.value);
    }
  });
  onUnmounted(() => {
    // 清空下防止内存溢出
    if (chartsRef.value) {
      myObserver.unobserve(chartsRef.value);
      myObserver.disconnect();
    }
  });
</script>

<style lang="less" scoped>
  .bug-trude-container {
    width: 100%;
    height: 100%;
    overflow: hidden;
    .bug-trude-container__title {
      text-align: center;
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 15px;
    }
    .bug-trude-container__date {
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
</style>
